<script setup lang="ts">
import Taro, { getCurrentInstance, showToast, showLoading, hideLoading, navigateBack } from '@tarojs/taro';
import { onMounted, reactive, ref } from 'vue';
import { useAddrStore, useAuthStore } from '@/store';
import { useGetAuthInfo } from '@/hooks';
import { SUCCESS_MSG_DURATION } from '@/constants';
import { storeToRefs } from 'pinia';
import { useNurseUser, useDict, use_hospital_dept_bed } from '@/service';

const { getDeptList, getbedList, getHospitalList } = use_hospital_dept_bed();

const { edit } = useNurseUser();

const { getDict } = useDict();

const { nurseUser } = storeToRefs(useAuthStore());

const { nurseUserFamilyList } = nurseUser.value;

const {
    router: {
        params: { id }
    }
}: any = getCurrentInstance();

const { getProvince, getCity, getCountry } = useAddrStore();

// definePageConfig({
//     navigationBarTitleText: id ? '设置被监护人信息' : '新增被监护人信息'
// });
Taro.setNavigationBarTitle({
    title: id ? '设置被监护人信息' : '新增被监护人信息'
});

const formData = ref<any>({
    name: '',
    sex: '',
    idcard: '',
    phone: '',
    area: '',
    areaName: '',
    address: '',
    isSelf: '',
    age: '',
    ageUnit: '岁',
    relation: '',
    relationName: '',
    record: '',
    hospital: '',
    hospitalName: '',
    dept: '',
    deptName: '',
    bed: '',
    bedName: '',
    status: '1',
    id: ''
});

const editIndex = ref(nurseUserFamilyList?.findIndex(item => item.id == id));

if (editIndex?.value !== undefined && id && nurseUserFamilyList) {
    formData.value = { ...nurseUserFamilyList[editIndex.value] };
}

onMounted(async () => {
    deptModule.onRefreshOptions();
});

const ruleForm = ref<any>(null);

const select = reactive({ text: '', value: '' });

const submit = async () => {
    const { valid } = await ruleForm.value.validate();

    if (!valid) return;

    showLoading({ title: '正在保存...' });

    if (id && editIndex.value !== undefined && nurseUserFamilyList) {
        nurseUserFamilyList[editIndex.value] = { ...formData.value };
    } else {
        nurseUserFamilyList?.push({
            ...formData.value,
            userId: nurseUser.value.id
        });
    }
    const data = { id: nurseUser.value.id, nurseUserFamilyList };

    const { error } = await edit(data);
    hideLoading();
    if (!error) {
        showToast({
            title: '保存成功',
            icon: 'success',
            duration: SUCCESS_MSG_DURATION
        });
        setTimeout(() => {
            navigateBack();
        }, 1200);
        useGetAuthInfo();
    }
};

// 函数校验
const customValidator = (val: string) => {
    if (/^\d+$/.test(val)) {
        return Promise.resolve();
    }
    if (!val) return Promise.resolve();
    return Promise.reject('年龄必须输入整数数字');
};

const areaModule: any = reactive({
    show: false,
    province: getProvince,
    city: [{}],
    country: [{}],
    town: [],
    showArea: () => {
        areaModule.show = !areaModule.show;
        if (areaModule.show) {
            select.text = '';
            select.value = '';
        }
    },
    onChange: (item: any) => {
        const { custom, next, value } = item;

        switch (custom) {
            case 'province':
                const city = getCity.filter(item => item.pid == value.id);
                areaModule.city = city;
                break;
            case 'city':
                const country = getCountry.filter(item => item.pid == value.id);
                areaModule.country = country;
                break;
            default:
                break;
        }
        // formData.value.areaName += value.name;
        // formData.value.area += value.id + "-";
        select.text += value.name;
        select.value += `${value.id}-`;
        const name = areaModule[next];
        if (!name?.length) {
            areaModule.show = false;
            formData.value.areaName = select.text;
            formData.value.area = select.value;
        }
    }
});

const relationModule: any = reactive({
    show: false,
    columns: [],
    showRelation: () => {
        relationModule.show = !relationModule.show;
        // if (relationModule.show) {
        //     formData.value.relation = '';
        //     formData.value.relationName = '';
        // }
    },
    confirm: ({ selectedValue, selectedOptions }: any) => {
        formData.value.relation = selectedValue[0];
        formData.value.relationName = selectedOptions[0].text;
        relationModule.show = false;
    }
});

const hospitalModule = reactive({
    show: false,
    showHospital: () => {
        hospitalModule.show = !hospitalModule.show;

        if (hospitalModule.show) {
            formData.value.hospital = '';
            formData.value.hospitalName = '';
        }
    },
    onChange: (items: any) => {
        if (items.length == 0) return;
        const item = items[items.length - 1];
        formData.value.hospital = item.key;
        formData.value.hospitalName = item.title;
        hospitalModule.show = false;
    },
    lazyLoad: async (pid: string) => {
        const { error, success } = await getHospitalList(pid);
        if (!error && success?.length > 0) {
            const list = success?.map((item: any) => {
                return {
                    value: item,
                    text: item.title
                };
            });
            return list;
        }
        return [];
    }
});

const deptModule = reactive({
    show: false,
    showDept: async () => {
        deptModule.show = !deptModule.show;
        if (deptModule.show) {
            formData.value.dept = '';
            formData.value.deptName = '';
            await deptModule.onRefreshOptions();
        }
    },
    options: [],
    onRefreshOptions: async () => {
        const { error, success } = await getDeptList('0', formData.value.hospital);
        if (!error && success?.length > 0) {
            const list = success?.map((item: any) => {
                return {
                    value: item,
                    text: item.title
                };
            });
            deptModule.options = list;
        } else {
            deptModule.options.length = 0;
            formData.value.dept = '';
            formData.value.deptName = '';
        }
    },
    onChange: (items: any) => {
        if (items.length == 0) return;
        const item = items[items.length - 1];
        formData.value.dept = item.key;
        formData.value.deptName = item.title;
        deptModule.show = false;
    },
    lazyLoad: async (pid: string) => {
        const { error, success } = await getDeptList(pid, formData.value.hospital);
        if (!error && success?.length > 0) {
            const list = success?.map((item: any) => {
                return {
                    value: item,
                    text: item.title
                };
            });
            return list;
        }
        return [];
    }
});

const bedModule: any = reactive({
    show: false,
    columns: [],
    onRefreshColumns: async () => {
        const { error, success } = await getbedList(formData.value.dept);

        if (!error && success?.length > 0) {
            const list = success?.map((item: any) => {
                return {
                    value: item,
                    text: item.name
                };
            });
            bedModule.columns = list;
        } else {
            bedModule.columns.length = 0;
        }
    },
    showBed: async () => {
        bedModule.show = !bedModule.show;

        if (bedModule.show) {
            formData.value.bed = '';
            formData.value.bedName = '';
            await bedModule.onRefreshColumns();
        }
    },
    confirm: ({ selectedValue }: any) => {
        formData.value.bed = selectedValue[0].id;
        formData.value.bedName = selectedValue[0].name;
        bedModule.show = false;
    }
});

onMounted(async () => {
    const data = await getDict('nurse_relation');
    const relations = data?.map(item => {
        return { text: item.itemText, value: item.itemValue };
    });
    if (relations) relationModule.columns = [...relations];
});
</script>
<template>
    <basic-layout>
        <!-- <custom-navbar :title="id ? '设置被监护人信息' : '新增被监护人信息'" showLeft /> -->
        <view class="w-375px flex-col-center">
            <view class="w-360px">
                <nut-form ref="ruleForm" class="w-full" :model-value="formData">
                    <nut-form-item label="姓名" prop="name" required :rules="[{ required: true, message: '请填写姓名' }]">
                        <nut-input v-model="formData.name" placeholder="请输入姓名" type="text" />
                    </nut-form-item>
                    <nut-form-item label="性别" prop="sex" required :rules="[{ required: true, message: '请选择性别' }]">
                        <NutRadioGroup v-model="formData.sex" direction="horizontal">
                            <nut-radio label="1">男</nut-radio>
                            <nut-radio label="2">女</nut-radio>
                        </NutRadioGroup>
                    </nut-form-item>
                    <nut-form-item label="身份证号" prop="phone" required :rules="[{ required: true, message: '请填写身份证号' }]">
                        <nut-input v-model="formData.idcard" placeholder="请填写身份证号" type="text" />
                    </nut-form-item>
                    <nut-form-item label="联系电话" prop="phone" required :rules="[{ required: true, message: '请填写联系电话' }]">
                        <nut-input v-model="formData.phone" placeholder="请输入联系电话" type="text" />
                    </nut-form-item>

                    <nut-form-item label="地区" prop="areaName" required :rules="[{ required: true, message: '请选择地区' }]">
                        <nut-input v-model="formData.areaName" readonly placeholder="请选择地区" type="text"
                            @click="areaModule.showArea" />
                        <nut-address v-model:visible="areaModule.show" :province="areaModule.province"
                            :city="areaModule.city" :country="areaModule.country" :town="areaModule.town"
                            custom-address-title="请选择所在地区" @change="areaModule.onChange"></nut-address>
                    </nut-form-item>
                    <nut-form-item label="详细地址" prop="address" required
                        :rules="[{ required: true, message: '请输入详细地址' }]">
                        <nut-input v-model="formData.address" placeholder="请输入详细地址" type="text" />
                    </nut-form-item>
                    <nut-form-item label="医院" prop="hospitalName" :rules="[{ required: false, message: '请选择医院' }]">
                        <nut-input v-model="formData.hospitalName" readonly placeholder="请选择医院" type="text"
                            @click="hospitalModule.showHospital" />
                        <basic-hospital v-model:visible="hospitalModule.show" :lazy-load="hospitalModule.lazyLoad"
                            :title="formData.defaultHospitalName" @change="hospitalModule.onChange" />
                    </nut-form-item>
                    <nut-form-item label="科室" prop="deptName" :rules="[{ required: false, message: '请输入医院' }]">
                        <view class="w-full flex justify-between items-center">
                            <nut-input v-model="formData.deptName" placeholder="请输入科室" type="text" />
                            <nut-button size="mini" type="default" @click="deptModule.showDept">选择科室</nut-button>
                        </view>
                        <basic-dept v-model:visible="deptModule.show" v-model:options="deptModule.options"
                            :lazy-load="deptModule.lazyLoad" :title="formData.defaultHospitalName"
                            @change="deptModule.onChange" />
                    </nut-form-item>
                    <nut-form-item label="床号" prop="bedName">
                        <view class="w-full">
                            <view class="w-full flex justify-between items-center">
                                <nut-input v-model="formData.bedName" placeholder="请输入床号" type="text" />
                                <nut-button size="mini" type="default" @click="bedModule.showBed">选择床号</nut-button>
                            </view>
                        </view>
                        <nut-popup v-model:visible="bedModule.show" position="bottom">
                            <nut-picker :columns="bedModule.columns" title="选择床号" @cancel="bedModule.show = false"
                                @confirm="bedModule.confirm" />
                        </nut-popup>
                    </nut-form-item>
                    <nut-form-item label="病历号" prop="record" :rules="[{ required: false, message: '' }]">
                        <nut-input v-model="formData.record" placeholder="请输入病历号" type="text" />
                    </nut-form-item>

                    <nut-form-item label="关系" prop="relationName">
                        <nut-input v-model="formData.relationName" readonly placeholder="请选择关系" type="text"
                            @click="relationModule.showRelation" />
                        <nut-popup v-model:visible="relationModule.show" position="bottom">
                            <nut-picker :columns="relationModule.columns" title="选择关系"
                                @cancel="relationModule.show = false" @confirm="relationModule.confirm" />
                        </nut-popup>
                    </nut-form-item>
                    <nut-form-item class="w-full flex-center" label="年龄" prop="age" :rules="[
                        { required: false, message: '' },
                        { validator: customValidator, message: '' }
                    ]">
                        <view class="flex-center w-full">
                            <nut-input v-model="formData.age" placeholder="请输入年龄" type="text" />
                            <NutRadioGroup v-model="formData.ageUnit" direction="horizontal">
                                <nut-radio label="岁">岁</nut-radio>
                                <nut-radio label="月">月</nut-radio>
                                <nut-radio label="天">天</nut-radio>
                            </NutRadioGroup>
                        </view>
                    </nut-form-item>
                    <nut-form-item label="能否自理" prop="is_self">
                        <NutRadioGroup v-model="formData.isSelf" direction="horizontal">
                            <nut-radio label="1">正常自理</nut-radio>
                            <nut-radio label="2">不能自理</nut-radio>
                        </NutRadioGroup>
                    </nut-form-item>
                    <nut-cell>
                        <basic-button text="保存" class="mt-2" @on-click="submit" />
                    </nut-cell>
                </nut-form>
            </view>
        </view>
    </basic-layout>
</template>
